package cn.jishiyu11.xeqb.utils

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.util.Log
import android.widget.Toast

import org.json.JSONException
import org.json.JSONObject

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.Inet6Address
import java.net.InetAddress
import java.net.MalformedURLException
import java.net.NetworkInterface
import java.net.SocketException
import java.net.URL
import java.net.URLConnection
import java.util.Enumeration
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 *
 * @类名称：NetWorkUtils
 * @类描述：
 * @创建时间：2015-6-26 上午11:43:44
 * @修改人：
 * @修改时间：2015-6-26 上午11:43:44
 * @修改备注：
 * @version
 */
object NetWorkUtils {

    /**
     * 获取ip地址  内网
     * @return
     */
    // skip ipv6
    val hostIP: String?
        get() {

            var hostIp: String? = null
            try {
                val nis = NetworkInterface.getNetworkInterfaces()
                var ia: InetAddress? = null
                while (nis.hasMoreElements()) {
                    val ni = nis.nextElement() as NetworkInterface
                    val ias = ni.inetAddresses
                    while (ias.hasMoreElements()) {
                        ia = ias.nextElement()
                        if (ia is Inet6Address) {
                            continue
                        }
                        val ip = ia!!.hostAddress
                        if ("127.0.0.1" != ip) {
                            hostIp = ia.hostAddress
                            break
                        }
                    }
                }
            } catch (e: SocketException) {
                Log.i("yao", "SocketException")
                e.printStackTrace()
            }

            return hostIp

        }


    /**
     * 获取外网的IP(要访问Url，要放到后台线程里处理)
     * @param @return
     * @return String
     * @throws
     * @Title: GetNetIp
     * @Description:
     */
    //            infoUrl = new URL("http://ip168.com/");
    val netIp: String
        get() {
            var infoUrl: URL? = null
            var inStream: InputStream? = null
            var ipLine = ""
            var httpConnection: HttpURLConnection? = null
            try {
                infoUrl = URL("http://pv.sohu.com/cityjson?ie=utf-8")
                val connection = infoUrl.openConnection()
                httpConnection = connection as HttpURLConnection
                val responseCode = httpConnection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inStream = httpConnection.inputStream
                    val reader = BufferedReader(
                            InputStreamReader(inStream!!, "utf-8"))
                    val strber = StringBuilder()
                    var line: String? = null
//                    while ((line = reader.readLine()) != null) {
//                        strber.append(line!! + "\n")
//                    }

                    while (true){
//                        line = reader.readLine()
//                        if (line !=null){
//                            strber.append(line!! + "\n")
//                        }else break
                        if (reader.readLine()!=null)strber.append(reader.readLine())else break

                    }

                    val pattern = Pattern
                            .compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))")
                    val matcher = pattern.matcher(strber.toString())
                    if (matcher.find()) {
                        ipLine = matcher.group()
                    }
                }
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    inStream!!.close()
                    httpConnection!!.disconnect()
                } catch (e: IOException) {
                    e.printStackTrace()
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }

            }
            Log.e("getNetIp", ipLine)
            return ipLine
        }

    /**
     * @param context
     * @return 返回有网络状态
     */
    fun isNetworkConnected(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable
            }
        }
        return false
    }

    /**
     * 网络连接提示
     *
     * @param context
     */
    fun netWorkStateTips(context: Context) {
        if (!isNetworkConnected(context))
            Toast.makeText(context, "无法连接到网络！", Toast.LENGTH_LONG).show()
    }

    /**
     * 判断是否是wifi连接
     * @param context
     * @return
     */
    fun isWifiConnected(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable
            }
        }
        return false
    }

    /**
     * GPS 是否打开
     *
     * @param context
     * @return
     */
    fun isGpsEnabled(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val accessibleProviders = locationManager.getProviders(true)
        return accessibleProviders != null && accessibleProviders.size > 0

    }

    fun openSetting(activity: Activity) {
        val intent = Intent("/")
        val cm = ComponentName("com.android.settings", "com.android.settings.WirelessSettings")
        intent.component = cm
        intent.action = "android.intent.action.VIEW"
        activity.startActivityForResult(intent, 0)
    }

    /**
     * 获取IP地址    外网
     * @return
     */
    fun GetNetIp(): String? {
        var infoUrl: URL? = null
        var inStream: InputStream? = null
        var line = ""
        try {
            infoUrl = URL("http://pv.sohu.com/cityjson?ie=utf-8")
            val connection = infoUrl.openConnection()
            val httpConnection = connection as HttpURLConnection
            val responseCode = httpConnection.responseCode
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.inputStream
                val reader = BufferedReader(InputStreamReader(inStream!!, "utf-8"))
                val strber = StringBuilder()
                while (true){
                    line = reader.readLine()
                    if (line!= null){
                        strber.append(line + "\n")
                    }else{
                        break
                    }
                }


                inStream.close()
                // 从反馈的结果中提取出IP地址
                val start = strber.indexOf("{")
                val end = strber.indexOf("}")
                val json = strber.substring(start, end + 1)
                if (json != null) {
                    try {
                        val jsonObject = JSONObject(json)
                        line = jsonObject.optString("cip")
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }

                }
                return line
            }
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return line
    }

}
